package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.LinkedList;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.FlowLayout;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.RandomColorTagView;
import com.pocketsweet.ui.uilib.TagLayout;
import com.pocketsweet.ui.uilib.TagView;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_edit_language)
public class EditLanguage extends BaseActivity implements OnClickListener {
	private HeaderLayout header;
	private MLUser mlUser = new MLUser();
	private ArrayList<String> languageList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络
	private ArrayList<String> languageRemoveList = new ArrayList<String>();// 将值传给编辑页面，编辑页面不用再请求网络
	private String[] stringLanguage = { "粤语", "普通话", "上海话", "湖南话", "四川话",
			"湖北话", "英语", "日语", "西班牙语", "韩语", "俄罗斯语" };

	@ViewInject(R.id.edtLanguage)
	private static EditText edtLanguage;

	@ViewInject(R.id.tagLanguage)
	private TagLayout tagLanguage;

	@ViewInject(R.id.RecommandTag)
	private FlowLayout RecommandTag;

	@ViewInject(R.id.btnAdd)
	private TextView btnAdd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlUser = UserService.getCurrentUser();
		initView();
		initTag();
		setHeaderFunction();
	}

	private void initView() {
		// languageList = getIntent().getStringArrayListExtra("language");
		if (mlUser.getLanguage() != null && mlUser.getLanguage().size() > 0) {
			addAllLabel();
		}
//		Log.e("==language", languageList.toString());
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edtLanguage.getWindowToken(), 0);
		edtLanguage.clearFocus();
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setMiddleText("语言");
		header.setRightText("");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				saveLanguage();
				EditLanguage.this.finish();
				// Intent intent = new Intent(EditNickName.this,
				// UserProfileEdit.class);
				// intent.putStringArrayListExtra("imgsPath",
				// UserProfile.imgsPath);
				// startActivity(intent);
			}
		});
	}

	private void initTag() {
		btnAdd.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 获取输入文字
				String label = edtLanguage.getText().toString();
				// 非有效标签直接返回
				if (TextUtils.isEmpty(label.trim())) {
					return;
				} else {
					// 有效标签，添加
					String temp;
					for (int i = 0; i < languageList.size(); i++) {
						temp = languageList.get(i);
						if (temp.equals(label)) {
							ToolKits.toast(EditLanguage.this, "已添加过");
							return;
						}
					}
					addLabel(label);
					mlUser.setLanguage(languageList);
				}
			}
		});

		for (int i = 0; i < stringLanguage.length; i++) {
			final RandomColorTagView itemView = new RandomColorTagView(
					EditLanguage.this);
			itemView.setText(stringLanguage[i]);
			final String tab = stringLanguage[i];
			itemView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
				}
			});
			itemView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String temp;
					for (int i = 0; i < languageList.size(); i++) {
						temp = languageList.get(i);
						if (temp.equals(tab)) {
							ToolKits.toast(EditLanguage.this, "已添加过");
							return;
						}
					}
					addLabel(tab);
					mlUser.setLanguage(languageList);
				}
			});
			RecommandTag.addView(itemView);
		}
	}

	/**
	 * 计算分享内容的字数，一个汉字=两个英文字母，一个中文标点=两个英文标点 注意：该函数的不适用于对单个字符进行计算，因为单个字符四舍五入后都是1
	 * 
	 * @param c
	 * @return
	 */
	private long calculateLength(CharSequence c) {
		double len = 0;
		for (int i = 0; i < c.length(); i++) {
			int tmp = (int) c.charAt(i);
			if (tmp > 0 && tmp < 127) {
				len += 0.5;
			} else {
				len++;
			}
		}
		return Math.round(len);
	}

	protected void addLabel(final String label) {
		if (calculateLength(label) > 5) {
			ToolKits.toast(EditLanguage.this, "超出字数限制");
			return;
		}
		if (tagLanguage.container.size() >= 8) {
			ToolKits.toast(EditLanguage.this, "您已经添加了8个标签了");
			return;
		}
		languageList.add(label);
		final TagView item = new TagView(EditLanguage.this);
		item.setName(label);
		item.getDelet().setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 移除标签
				Animation anim = AnimationUtils.loadAnimation(
						EditLanguage.this, R.anim.unzoom_out);
				anim.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationRepeat(Animation animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationEnd(Animation animation) {
						tagLanguage.removeView(item.getTag().toString());
						String temp;
						for (int i = 0; i < languageList.size(); i++) {
							temp = languageList.get(i);
							if (temp.equals(label)) {
								languageList.remove(i);
								languageRemoveList.add(label);
								mlUser.removeLanguage(languageRemoveList);
								break;
							}
						}
					}
				});
				item.startAnimation(anim);

			}
		});
		tagLanguage.addView(item);
		edtLanguage.setText("");
	}

	protected void addAllLabel() {
		LinkedList<View> list = new LinkedList<View>();
		for (final String label : mlUser.getLanguage()) {
			if (calculateLength(label) > 5) {
				ToolKits.toast(EditLanguage.this, "超出字数限制");
				return;
			}
			if (tagLanguage.container.size() >= 8) {
				ToolKits.toast(EditLanguage.this, "您已经添加了8个标签了");
				return;
			}
			languageList.add(label);
			final TagView item = new TagView(EditLanguage.this);
			item.setName(label);
			item.getDelet().setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// 移除标签
					Animation anim = AnimationUtils.loadAnimation(
							EditLanguage.this, R.anim.unzoom_out);
					anim.setAnimationListener(new AnimationListener() {

						@Override
						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationEnd(Animation animation) {
							tagLanguage.removeView(item.getTag().toString());
							String temp;
							for (int i = 0; i < languageList.size(); i++) {
								temp = languageList.get(i);
								if (temp.equals(label)) {
									languageList.remove(i);
									languageRemoveList.add(label);
									mlUser.removeLanguage(languageRemoveList);
									break;
								}
							}
						}
					});
					item.startAnimation(anim);

				}
			});
			list.add(item);
		}
		tagLanguage.addALLView(list);
	}

	private void saveLanguage() {
		mlUser.saveInBackground(new SaveCallback() {
			@Override
			public void done(AVException arg0) {
				// TODO Auto-generated method stub
				if (arg0 == null) {
					// notify
					ProfileEdit.notifyBack();
					edtLanguage.setText("");
				} else {
//					Log.e("==error", "添加语言失败" + arg0.getMessage());
				}
			}
		});
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 此处写处理的事件
			saveLanguage();
			EditLanguage.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
